package com.asman.worker.multishow

import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.VideoView
import androidx.core.app.ActivityCompat
import androidx.core.net.toUri
import androidx.fragment.app.FragmentActivity
import androidx.viewpager.widget.PagerAdapter
import com.asman.base.lib.glide.GlideApp
import com.asman.customerview.extensions.isMulti
import com.asman.worker.R
import com.asman.worker.utils.ImageDownloadUtils
import com.github.chrisbanes.photoview.PhotoView
import ossZip
import showToast
import java.util.*

/**
 * Created by Administrator on 2016/11/29.
 */
open class MultiShowAdapter<T>(
    private val datas: List<T>,
    private val context: Activity,
    private val ossZip: Boolean /*是否需要压缩*/,
    private val callBack: CallBack<T>?
) : PagerAdapter() {
    private var mChildCount = 0
    private val views = ArrayList<View>()

    private var primaryItem: View? = null

    private var imageDownloadUtils: ImageDownloadUtils? = null

    init {
        if (context is FragmentActivity) {
            imageDownloadUtils = ImageDownloadUtils(context)
        }
    }

    interface CallBack<T> {
        fun getUrl(t: T): String
    }

    override fun getCount(): Int {
        return datas.size
    }

    override fun isViewFromObject(arg0: View, arg1: Any): Boolean {
        return arg0 === arg1
    }

    override fun destroyItem(container: ViewGroup, position: Int, any: Any) {
        container.removeView(any as View)
        views.remove(any)
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val url = callBack?.getUrl(datas[position])
        return if (url.isMulti()) {
            initMulti(container, url)
        } else {
            initImage(container, position, url)
        }
    }

    //视频Item
    private fun initMulti(container: ViewGroup, url: String?): Any {
        var urlFinal = url
        val view = LayoutInflater.from(container.context)
            .inflate(R.layout.item_multi_show, container, false)
        views.add(view)
        val imageView = view.findViewById<ImageView>(R.id.image_view)
        val viewBg = view.findViewById<View>(R.id.view)
        val ivPlay = view.findViewById<ImageView>(R.id.iv_play)
        val videoView = view.findViewById<VideoView>(R.id.video_view)
        val mc = MyMediaController(context, true)
        val progressBar = view.findViewById<ProgressBar>(R.id.progress_bar)
        val iv_download = view.findViewById<ImageView>(R.id.iv_download)

        val progress_bar_download = view.findViewById<ProgressBar>(R.id.progress_bar_download)

        val isDownload = FileUtils.isFileDownloaded(urlFinal)
        //如果视频文件已经下载过了
        if (isDownload) {
            iv_download.visibility = View.GONE
            urlFinal = FileUtils.getOriginFilePath(urlFinal)
        } else {
            iv_download.visibility = View.VISIBLE
            iv_download.setOnClickListener {
                //下载
                if (context is FragmentActivity) {
                    iv_download.visibility = View.GONE
                    progress_bar_download.visibility = View.VISIBLE
                    imageDownloadUtils?.startDownload(
                        urlFinal,
                        "牛大匠",
                        FileUtils.generatorLocalFileName(urlFinal)
                    ) {
                        //下载成功，UI修改
                        progress_bar_download.visibility = View.GONE
                        iv_download.visibility = View.GONE
                        urlFinal = FileUtils.getOriginFilePath(urlFinal)
                        videoView.setVideoURI(urlFinal?.toUri())
                    }
                } else {
                    showToast("当前上下文不是FragmentActivity")
                }
            }
        }

//        ivCloseVideo.setOnClickListener {
//            videoView.stopPlayback()
//            mc.hide()
//            onBackPressed()
//        }
        mc.setOnShowOrHideListener(object : MyMediaController.OnShowOrHideListener {
            override fun show() {
//                ivCloseVideo.visibility = View.VISIBLE
            }

            override fun hide() {
                if (videoView.visibility == View.VISIBLE) {
//                    ivCloseVideo.visibility = View.GONE
                }
            }
        })
        videoView.setMediaController(mc)
        videoView.setVideoURI(urlFinal?.toUri())
        val aa = if (isDownload) urlFinal else urlFinal.ossZip(400)
        GlideApp.with(context)
            .load(aa)
            .thumbnail(0.05f)
            .fitCenter().into(imageView)

        viewBg.visibility = View.VISIBLE
        ivPlay.visibility = View.VISIBLE
        videoView.visibility = View.GONE

        viewBg.setOnClickListener {
            videoView.visibility = View.VISIBLE
            if (!videoView.isPlaying) {
                viewBg.visibility = View.GONE
                videoView.start()
                progressBar.visibility = View.VISIBLE
                videoView.setOnCompletionListener {
                    //播放结束
                    viewBg.visibility = View.VISIBLE
                    ivPlay.visibility = View.VISIBLE
                    imageView.visibility = View.VISIBLE
                    videoView.visibility = View.GONE
//                    ivCloseVideo.visibility = View.VISIBLE
                }
                videoView.setOnPreparedListener {
                    ivPlay.postDelayed({
                        ivPlay.visibility = View.GONE
                        imageView.visibility = View.GONE
                        progressBar.visibility = View.GONE
                    }, 1000)
                }
            }
        }
        container.addView(view)
        return view
    }

    //图片item
    private fun initImage(container: ViewGroup, position: Int, url: String?): Any {
        var urlFinal = url
        val view = LayoutInflater.from(container.context)
            .inflate(R.layout.item_multi_image_show, container, false)
        val photoView = view.findViewById<PhotoView>(R.id.photoView)
        val progress_bar_download = view.findViewById<ProgressBar>(R.id.progress_bar_download)
        val iv_download = view.findViewById<ImageView>(R.id.iv_download)

        val isDownload = FileUtils.isFileDownloaded(urlFinal)
        //如果视频文件已经下载过了
        if (isDownload) {
            iv_download.visibility = View.GONE
            urlFinal = FileUtils.getOriginFilePath(urlFinal)
        } else {
            iv_download.visibility = View.VISIBLE
            iv_download.setOnClickListener {
                //下载
                if (context is FragmentActivity) {
                    iv_download.visibility = View.GONE
                    progress_bar_download.visibility = View.VISIBLE
                    imageDownloadUtils?.startDownload(
                        urlFinal, "牛大匠", FileUtils.generatorLocalFileName(urlFinal)
                    ) {
                        //下载成功，UI修改
                        progress_bar_download.visibility = View.GONE
                        iv_download.visibility = View.GONE
                        urlFinal = FileUtils.getOriginFilePath(urlFinal)
                        GlideApp.with(context)
                            .load(urlFinal)
                            .override(3000, 3000)
                            .fitCenter()
                            .dontAnimate()
                            .into(photoView)
                    }
                } else {
                    showToast("当前上下文不是FragmentActivity")
                }
            }
        }

        views.add(view)

        photoView.transitionName = "imageView$position"
        photoView.mediumScale = 2.5f
        photoView.maximumScale = 5.0f
        photoView.scaleType = ImageView.ScaleType.FIT_CENTER

        if (isDownload) {
            GlideApp.with(context)
                .load(urlFinal)
                .override(3000, 3000)
                .fitCenter()
                .into(photoView)
        } else {
            GlideApp.with(context)
                .load(urlFinal.ossZip(300))
                .placeholder(R.drawable.image_default_192)
                .thumbnail(0.05f)
                .fitCenter()
                .into(photoView)
        }
        photoView.setOnViewTapListener { _, _, _ ->
            onBackPressed()
        }
        container.addView(view)
        return view
    }

    //停止播放不是当前页的视频
    fun stopOtherVideo() {
        views.map {
            it.findViewById<VideoView>(R.id.video_view)?.stopPlayback()
            it.findViewById<ImageView>(R.id.iv_play)?.visibility = View.VISIBLE
            it.findViewById<View>(R.id.view)?.visibility = View.VISIBLE
            it.findViewById<ImageView>(R.id.image_view)?.visibility = View.VISIBLE
            it.findViewById<VideoView>(R.id.video_view)?.visibility = View.GONE
//            it.findViewById<ImageView>(R.id.iv_close_video)?.visibility = View.VISIBLE
            it.findViewById<ProgressBar>(R.id.progress_bar)?.visibility = View.GONE
        }
    }

    /**
     * @param currentView 当前展示的View
     */
    fun onBackPressed() {
        ActivityCompat.finishAfterTransition(context)
    }

    override fun notifyDataSetChanged() {
        mChildCount = count
        super.notifyDataSetChanged()
    }

    override fun getItemPosition(`object`: Any): Int {
        if (mChildCount > 0) {
            mChildCount--
            return POSITION_NONE
        }
        return super.getItemPosition(`object`)
    }

    override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) {
        primaryItem = `object` as View
    }

}
